package com.zenithmind.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenithmind.user.mapper.PermissionMapper;
import com.zenithmind.user.pojo.domain.Permission;
import com.zenithmind.user.pojo.domain.RolePermission;
import com.zenithmind.user.pojo.query.PermissionQuery;
import com.zenithmind.user.pojo.vo.PermissionVO;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.user.service.PermissionService;
import com.zenithmind.user.service.RolePermissionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zenithmind.common.annotation.DataCache;
import com.zenithmind.common.annotation.DataCacheEvict;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Autowired
    private RolePermissionService rolePermissionService;

    /**
     * 权限分页查询
     *
     * @param permissionQuery 权限查询对象，包含查询条件和分页信息
     * @return 分页查询结果，包含权限列表和分页相关数据
     */
    @Override
    @DataCache(prefix = "permission:page", key = "#permissionQuery.toString()", expireTime = 1800)
    public PageResult<PermissionVO> page(PermissionQuery permissionQuery) {
        Page<Permission> page = permissionQuery.toPage();
        LambdaQueryWrapper<Permission> wrapper = new LambdaQueryWrapper<>();

        // 添加查询条件
        wrapper.like(StringUtils.isNotBlank(permissionQuery.getPermissionName()), Permission::getPermissionName, permissionQuery.getPermissionName())
                .like(StringUtils.isNotBlank(permissionQuery.getPermissionCode()), Permission::getPermissionCode, permissionQuery.getPermissionCode())
                .eq(permissionQuery.getType() != null, Permission::getType, permissionQuery.getType())
                .eq(permissionQuery.getStatus() != null, Permission::getStatus, permissionQuery.getStatus())
                .orderByAsc(Permission::getSortOrder);

        Page<Permission> permissionPage = page(page, wrapper);

        // 转换为VO对象
        List<PermissionVO> permissionVOList = permissionPage.getRecords().stream().map(permission -> {
            PermissionVO permissionVO = new PermissionVO();
            BeanUtils.copyProperties(permission, permissionVO);
            return permissionVO;
        }).collect(Collectors.toList());

        return new PageResult<>(permissionVOList, permissionPage.getTotal(), permissionPage.getCurrent(), permissionPage.getSize());
    }

    /**
     * 获取权限树
     *
     * @return 树形结构的权限列表
     */
    @Override
    @DataCache(prefix = "permission:tree", expireTime = 3600)
    public List<PermissionVO> getPermissionTree() {
        LambdaQueryWrapper<Permission> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Permission::getSortOrder);
        // 获取所有权限
        List<Permission> permissions = list(wrapper);

        // 转换为VO对象
        List<PermissionVO> permissionVOList = permissions.stream().map(permission -> {
            PermissionVO permissionVO = new PermissionVO();
            BeanUtils.copyProperties(permission, permissionVO);
            return permissionVO;
        }).collect(Collectors.toList());
        return permissionVOList;
    }

    /**
     * 根据角色ID获取权限列表
     *
     * @param roleId 角色ID
     * @return 角色对应的权限列表
     */
    @Override
    @DataCache(prefix = "permission:role", key = "#roleId", expireTime = 3600)
    public List<PermissionVO> getByRoleId(String roleId) {
        if (StringUtils.isBlank(roleId)) {
            throw new RuntimeException("角色ID不能为空");
        }

        // 获取角色权限关联
        LambdaQueryWrapper<RolePermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RolePermission::getRoleId, roleId);
        List<RolePermission> rolePermissions = rolePermissionService.list(wrapper);

        if (rolePermissions == null || rolePermissions.isEmpty()) {
            return new ArrayList<>();
        }

        // 获取权限ID列表
        List<String> permissionIds = rolePermissions.stream()
                .map(RolePermission::getPermissionId)
                .collect(Collectors.toList());

        // 获取权限列表
        List<Permission> permissions = listByIds(permissionIds);

        // 转换为VO对象
        return permissions.stream().map(permission -> {
            PermissionVO permissionVO = new PermissionVO();
            BeanUtils.copyProperties(permission, permissionVO);
            return permissionVO;
        }).collect(Collectors.toList());
    }

    /**
     * 根据权限ID获取权限信息
     *
     * @param id 权限ID
     * @return 权限信息
     */
    @Override
    @DataCache(prefix = "permission", key = "#id", expireTime = 3600)
    public PermissionVO getPermissionById(String id) {
        if (StringUtils.isBlank(id)) {
            throw new RuntimeException("权限ID不能为空");
        }

        Permission permission = getById(id);
        if (permission == null) {
            throw new RuntimeException("权限不存在");
        }

        PermissionVO permissionVO = new PermissionVO();
        BeanUtils.copyProperties(permission, permissionVO);

        return permissionVO;
    }

    /**
     * 新增或更新权限
     *
     * @param permission 权限对象
     * @return 是否成功
     */
    @DataCacheEvict(prefix = "permission", allEntries = true)
    public boolean saveOrUpdatePermission(Permission permission) {
        return saveOrUpdate(permission);
    }

    /**
     * 删除权限
     *
     * @param id 权限ID
     * @return 是否成功
     */
    @DataCacheEvict(prefix = "permission", allEntries = true)
    public boolean removePermission(String id) {
        return removeById(id);
    }
}
